package com.example.controller;

import com.example.constant.Constant;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录模块")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录,只用传username和password")
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        //调用业务层：登录功能
        User loginUser = userService.login(user);

        //判断：登录用户是否存在
        if(loginUser !=null ){
            //自定义信息
            Map<String , Object> claims = new HashMap<>();
            claims.put(Constant.JWT_CLAIMS_USER_ID, loginUser.getUserID());
            claims.put(Constant.JWT_CLAIMS_USERNAME,loginUser.getUsername());

            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            LoginVO loginVO = new LoginVO();
            loginVO.setUserType(loginUser.getUserType()).setToken(token)
                    .setUserID(loginUser.getUserID());
            return Result.success(loginVO);
        }
        return Result.error("用户名或密码错误");
    }
}
